<script>
import { notEmpty } from "./utils";

export default {
  components: {},
  emits: ["toggle"],
  data() {
    return {
      formData: {
        username: "fox",
        password: "123456",
      },
      errMsg: "",
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 16,
            message: "长度在 3 到 16 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 20,
            message: "长度在 6 到 20 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    async submit() {
      try {
        await this.$refs.form.validate();
        // 发起请求
        const { data } = await this.$request("/login", {
          method: "post",
          data: this.formData,
        });
        if (data.success) {
          // 执行登录成功后的操作
          // 将用户信息存储到 vuex 中
          this.$store.commit("login", data.user);
          // 跳转到首页
          this.$router.push("/");
        } else {
          if (notEmpty(data.errors)) {
            this.errMsg = data.errors.username.join(", ");
          }
        }
      } catch (error) {
        console.log(error);
      }
    },
  },
};
</script>
<template>
  <ElForm
    ref="form"
    :model="formData"
    :rules="rules"
    label-position="left"
    label-width="120px"
    status-icon
  >
    <ElFormItem label="用户名" prop="username" :error="errMsg">
      <ElInput v-model="formData.username" />
    </ElFormItem>
    <ElFormItem label="密码" prop="password">
      <ElInput type="password" v-model="formData.password" />
    </ElFormItem>
    <ElFormItem>
      <ElButton @click="submit">登录</ElButton>
      <ElButton type="primary" link @click="$emit('toggle')">前往注册</ElButton>
    </ElFormItem>
  </ElForm>
</template>
